import {
	ApiResponse, RequestConfig, RequestFileConfig, TIME_OUT, CONTENT_TYPE_JSON, createHeaders
} from "./http_config";
import { showLoading, hideLoading } from "@/utils/ui/loading_util"
import { getRequestUriType } from "../config";
import { error, log } from "@/utils/common/log_util";
import { getToken } from "@/utils/busnisess/user_util";
import { isNotEmpty } from "@/utils/common/object_util";
import { showToast } from "@/utils/ui/toast_util";
import { goLoginPage } from "@/utils/router/router_util";
import { AppVersionData } from "@/api/entity/basic";
import { checkAppUpdate } from "@/utils/common/app_util";

/**
 * 网络请求工具
 */
export const request = <T>(config : RequestConfig) => {
	return new Promise<ApiResponse<T>>((resolve, reject) => {
		const { url, method, data, isShowLoading, contentType } = config;
		if (isShowLoading) {
			showLoading()
		}
		const token = getToken()
		const header = createHeaders(contentType ?? CONTENT_TYPE_JSON, token)
		log(`请求地址：${getRequestUriType()}${url}`)
		log(`请求方式:${method}`)
		log(`请求数据：${JSON.stringify(data)}`)
		log(`请求头：${JSON.stringify(header)}`)
		uni.request({
			url: `${getRequestUriType()}${url}`,
			method: method,
			data: data,
			timeout: TIME_OUT,
			header: header,
			// 响应成功
			success(res) {
				if (isShowLoading) {
					hideLoading()
				}
				if (res.statusCode >= 200 && res.statusCode < 300) {
					//仅限APP可获取版本更新信息
					//#ifdef APP-PLUS
					const versionInfo = res.header['versionData']
					if (isNotEmpty(versionInfo)) {
						_versionCallback(url, versionInfo)
					}
					//#endif
					log(`响应结果：${JSON.stringify(res.data)}`)
					let data = res.data as ApiResponse<T>
					switch (data.errno) {
						case 501: 	    //token失效 重新登录
							goLoginPage()
							reject(res)
							break
						case 0:        //成功
						case 753:     //新用户标记
						case 405:     //不可退款标记
						case 300100:  //CA证书过期标记
							resolve(data)
							break
						default:
							if (isNotEmpty(data.errmsg)) {
								showToast(data.errmsg)
							}
							reject(res)
							break
					}
				}
			},
			fail(err) {
				if (isShowLoading) {
					hideLoading()
				}
				log("errorMsg:" + err.errMsg)
				//响应失败，网络错误，调用reject
				showToast('网络异常，请稍后再试！')
				reject(err)
			},
		})
	})
}

//上传图片
export const uploadImgFile = <T>(config : RequestFileConfig) => {
	return new Promise<ApiResponse<T>>((resolve, reject) => {
		const { url, filePath, formData, isShowLoading } = config;
		if (isShowLoading) {
			showLoading()
		}
		const token = getToken()
		const header = createHeaders(CONTENT_TYPE_JSON, token)
		log(`请求地址：${getRequestUriType()}${url}`)
		log(`请求数据：${JSON.stringify(formData)}`)
		log(`请求头：${JSON.stringify(header)}`)
		uni.uploadFile({
			url: `${getRequestUriType()}${url}`,
			filePath: filePath,
			name: 'file',
			formData: formData,
			timeout: TIME_OUT,
			header: header,
			success: (res) => {
				if (isShowLoading) {
					hideLoading()
				}
				if (res.statusCode >= 200 && res.statusCode < 300) {
					log(`响应结果：${res.data}`)
					let data = JSON.parse(res.data) as ApiResponse<T>
					switch (data.errno) {
						case 501: 	    //token失效 重新登录
							goLoginPage()
							reject(res)
							break
						case 0:        //成功
						case 753:     //新用户标记
						case 405:     //不可退款标记
						case 300100:  //CA证书过期标记
							resolve(data)
							break
						default:
							if (isNotEmpty(data.errmsg)) {
								showToast(data.errmsg)
							}
							reject(res)
							break
					}
				}
			},
			fail: (err) => {
				if (isShowLoading) {
					hideLoading()
				}
				log("errorMsg:" + err.errMsg)
				//响应失败，网络错误，调用reject
				showToast('网络异常，请稍后再试！')
				reject(err)
			}
		})
	})
}

//获取成功
export const isSuccess = (errno ?: number) => {
	return errno == 0
}

//获取成功且数据存在
export const isSuccessWithData = <T>(errno ?: number, data ?: T) : boolean => {
	return isSuccess(errno) && data != null && data != undefined
}

//token失效
export const isTokenFailed = (errno ?: number) => {
	return errno == 501
}

//是否新用户标记
export const isNewUserCode = (errno ?: number) => {
	return errno == 753
}

//是否不可退款标记
export const isRefundOrderCode = (errno ?: number) => {
	return errno == 405
}

//CA是否证书过期标记
export const isCertificateExpired = (errno ?: number) => {
	return errno == 300100
}

//检查APP更新
const _versionCallback = (path : string, versionInfo ?: string) : void => {
	if (isNotEmpty(versionInfo)) {
		if (path.includes('doctor/auth/login')) {
			return
		}
		const versionData = JSON.parse(versionInfo) as AppVersionData
		checkAppUpdate(versionData)
	}
}